<template>
  <q-card-actions align="right" v-if="!isReadOnly &&display=='cur_tab'">
    <q-btn label="Create" class="default-btn"  @click="assignTask = true" />
  </q-card-actions>
  <q-dialog v-model="assignTask">
      <AssignOrderTask
      :style="'create'"
      v-if="props.orderId&&props.stock_code"
      :order-id="props.orderId"
      :stock_code="props.stock_code"
      @close="closeDialog"
      @update="onUpdateTask"
      ></AssignOrderTask>
  </q-dialog>
  <!-- <ScrollArea :bot-margin="50"> -->
  <div class="sub-header">
    {{ 'Tasks List' }}
  </div>
  <q-table
    class="q-ma-sm my-table"
    :rows="state.data"
    :columns="props.isHideCol?currentTaskCol:cols"
    :rows-per-page-options="[5]"
    wrap-cells
  >
    <template v-slot:body-cell-task="props">
      <q-td
        :props="props"
        :class="props.row.has_eform?getOverAllresultCss(props.row):props.row.role_result != 'Pass' ? 'fail' : ''"
      >
        {{ props.row.stock_item_task.name }}
    </q-td>
    </template>

    <template v-slot:body-cell-tester="props">
      <q-td :props="props">
        {{ props.row.role }}
      </q-td>
    </template>

    <template v-slot:body-cell="props">
      <q-td
        :props="props"
        :class="props.row.has_eform?getOverAllresultCss(props.row):props.row.role_result != 'Pass' ? 'fail' : ''"
      >
        {{ props.value }}
      </q-td>
    </template>

    <template v-slot:body-cell-done_by="props">
      <q-td
        :props="props"
        :class="props.row.has_eform?getOverAllresultCss(props.row):props.row.role_result != 'Pass' ? 'fail' : ''"
      >
        {{ props.row.done_by ? props.row.done_by.username : '' }} <br> 
        {{ props.row.done_by_datetime ? props.row.done_by_datetime.split('T')[0]: ''}}
      </q-td>
    </template>
    <template v-slot:body-cell-verify_by="props">
      <q-td
        :props="props"
        :class="props.row.has_eform?getOverAllresultCss(props.row):props.row.role_result != 'Pass' ? 'fail' : ''"
      >
        <div v-if="isUpdateVeriAndEnd">
          <q-btn size="xs" outline rounded color="primary" label="Assign" @click="openSearchDialog(props.row, 'verify')"></q-btn>
          <div>assign: {{props.row.verify_user?.username? props.row.verify_user.username: 'anyone'}}</div>
        </div>
        {{ props.row.verify_by ? props.row.verify_by.username : '' }} <br> 
        {{ props.row.verify_by_datetime ? props.row.verify_by_datetime.split('T')[0]: ''}}
      </q-td>
    </template>
    <template v-slot:body-cell-endorse_by="props">
      <q-td
        :props="props"
        :class="props.row.has_eform?getOverAllresultCss(props.row):props.row.role_result != 'Pass' ? 'fail' : ''"
      >
        <div v-if="isUpdateVeriAndEnd">
          <q-btn size="xs" outline rounded color="primary" label="Assign" @click="openSearchDialog(props.row, 'endorse')"></q-btn>
          <div>assign: {{props.row.endorse_user?.username? props.row.endorse_user.username: 'anyone'}}</div>
        </div>
        {{ props.row.endorse_by ? props.row.endorse_by.username : '' }} <br> 
        {{ props.row.endorse_by_datetime ? props.row.endorse_by_datetime.split('T')[0]: ''}}
      </q-td>
    </template>


    <template v-slot:body-cell-eform="props">
      <q-td
        :props="props"
        :class="props.row.has_eform?getOverAllresultCss(props.row):props.row.role_result != 'Pass' ? 'fail' : ''"
      >
        <form :action="getEformUrl(props.row)" target="_blank" method="post">
          <q-btn v-if="props.row.has_eform" type="submit" class="e-form-btn">
            <div class="fal">
              <img :src="eformIcon" />
              <span class="q-px-sm cap"> e-form </span>
            </div></q-btn
          >
          <input type="hidden" name="token" :value="user.token" />
        </form>
      </q-td>
    </template>

    <template v-slot:body-cell-result="props">
      <q-td
        :props="props"
        :class="props.row.has_eform?getOverAllresultCss(props.row):props.row.role_result != 'Pass' ? 'fail' : ''"
      >
   
    
            <q-radio
              size="xs"
              @update:model-value="saveFn"
              v-model="props.row.role_result"
              val="Pass"
              label="Pass"
              :disable="props.row.has_eform"
            />
            <q-radio
              size="xs"
              @update:model-value="saveFn"
              v-model="props.row.role_result"
              val="Fail"
              label="Fail"
              :disable="props.row.has_eform"
            />
            <q-radio
              size="xs"
              @update:model-value="saveFn"
              v-model="props.row.role_result"
              val="N/A"
              label="N/A"
              :disable="props.row.has_eform"
            />
   
   
      </q-td>
    </template>
  </q-table>

  <div class="sub-header" 
  v-if="state.newAdd.length>0"
  >
    {{ 'New ADD Tasks List' }}
  </div>
  <q-table
  v-if="state.newAdd.length>0"
    class="q-ma-sm my-table"
    :rows="state.newAdd"
    :columns="props.isHideCol?currentTaskCol:cols"
    :rows-per-page-options="[5]"
    wrap-cells
  >
    <template v-slot:body-cell-task="props">
      <q-td
        :props="props"
        :class="props.row.has_eform?getOverAllresultCss(props.row):props.row.role_result != 'Pass' ? 'fail' : ''"
      >
        {{ props.row.name }}
      </q-td>
    </template>

    <template v-slot:body-cell-tester="props">
      <q-td :props="props">
        {{ props.row.role }}
      </q-td>
    </template>

    <template v-slot:body-cell="props">
      <q-td
        :props="props"
        :class="props.row.has_eform?getOverAllresultCss(props.row):props.row.role_result != 'Pass' ? 'fail' : ''"
      >
        {{ props.value }}
      </q-td>
    </template>

    <template v-slot:body-cell-eform="props">
      <q-td
        :props="props"
        :class="props.row.has_eform?getOverAllresultCss(props.row):props.row.role_result != 'Pass' ? 'fail' : ''"
      >
        <form :action="getEformUrl(props.row)" target="_blank" method="post">
          <q-btn v-if="props.row.has_eform" type="submit" class="e-form-btn">
            <div class="fal">
              <img :src="eformIcon" />
              <span class="q-px-sm cap"> e-form </span>
            </div>
            </q-btn
          >
          <input type="hidden" name="token" :value="user.token" />
        </form>
      </q-td>
    </template>

    <template v-slot:body-cell-result="props">
      <q-td
        :props="props"
        :class="props.row.has_eform?getOverAllresultCss(props.row):props.row.role_result != 'Pass' ? 'fail' : ''"
      >    
            <q-radio
              size="xs"
              @update:model-value="saveNewAddFn"
              v-model="props.row.role_result"
              val="Pass"
              label="Pass"
              :disable="props.row.has_eform"
            />
            <q-radio
              size="xs"
              @update:model-value="saveNewAddFn"
              v-model="props.row.role_result"
              val="Fail"
              label="Fail"
              :disable="props.row.has_eform"
            />
            <q-radio
              size="xs"
              @update:model-value="saveNewAddFn"
              v-model="props.row.role_result"
              val="N/A"
              label="N/A"
              :disable="props.row.has_eform"
            />
   
   
      </q-td>
    </template>

    <template v-slot:body-cell-done_by="props">
      <q-td
        :props="props"
        :class="props.row.has_eform?getOverAllresultCss(props.row):props.row.role_result != 'Pass' ? 'fail' : ''"
      >
        {{ props.row.done_by ? props.row.done_by.username : '' }} <br> 
        {{ props.row.done_by_datetime ? props.row.done_by_datetime.split('T')[0]: ''}}
      </q-td>
    </template>

    <template v-slot:body-cell-verify_by="props">
      <q-td
        :props="props"
        :class="props.row.has_eform?getOverAllresultCss(props.row):props.row.role_result != 'Pass' ? 'fail' : ''"
      >
        <span v-if="!props.row.is_endorse_required">
          {{ 'N/A' }}
        </span>
        <span v-else>
          {{ props.row.verify_by ? props.row.verify_by.username : '' }} <br> 
          {{ props.row.verify_by_datetime ? props.row.verify_by_datetime.split('T')[0]: ''}}
        </span>
      </q-td>
    </template>
    <template v-slot:body-cell-endorse_by="props">
      <q-td
        :props="props"
        :class="props.row.has_eform?getOverAllresultCss(props.row):props.row.role_result != 'Pass' ? 'fail' : ''"
      >
        <span v-if="!props.row.is_endorse_required">
          {{ 'N/A' }}
        </span>
        <span v-else>
          {{ props.row.endorse_by ? props.row.endorse_by.username : '' }} <br> 
          {{ props.row.endorse_by_datetime ? props.row.endorse_by_datetime.split('T')[0]: ''}}
        </span>
      </q-td>
    </template>

    <template v-slot:body-cell-action="props">
      <q-td
      :class="props.row.has_eform?getOverAllresultCss(props.row):props.row.role_result != 'Pass' ? 'fail' : ''"
      >
        <q-btn
          class="del-btn"
          icon="delete"
          flat
          round
          @click="deleteFn(props.row.id)"
        />
      </q-td>
    </template>
  </q-table>
  <!-- </ScrollArea> -->

  <!-- 搜索弹窗 -->
  <q-dialog  v-model="SearchDialog">
    <q-card style="width: 50vw;max-width:58vw;" class="overflow-hidden card-radius" >
      <q-toolbar class="popup-header">
        <q-toolbar-title class="q-ma-md cap">
          Search  Result
        </q-toolbar-title>
        <q-space />
        <q-btn
        icon="close"
        size="lg"
        flat
        round
        dense
        v-close-popup
        />
      </q-toolbar>
      <div class="content mt20">
        <div class="flex-center">
          <div class="flex1 text-sm q-pa-sm">
            <div class="row">
              <div class="col-4 fac">Username:</div>
              <div class="col-8">
                <q-input
                  class="input-css"
                  borderless
                  dense
                  v-model="searchInfo.username"
                >
                  <template v-slot:append>
                    <img class="delImgClass" :src="delImg" alt="" v-if="searchInfo.username" @click="searchInfo.username = ''">
                  </template>
                </q-input>
              </div>
            </div>
          </div>
          <div class="flex1 text-  q-pa-sm">
            <div class="row">
              <div class="col-4 fac">E-mail:</div>
              <div class="col-8">
                <q-input
                  class="input-css"
                  borderless
                  dense
                  v-model="searchInfo.email"
                >
                  <template v-slot:append>
                    <img class="delImgClass" :src="delImg" alt="" v-if="searchInfo.email" @click="searchInfo.email = ''">
                  </template>
                </q-input>
              </div>
            </div>
          </div>
        </div>
      </div>
      <q-card-actions class="justify-evenly q-pa-md">
        <q-btn label="Search" class="default-btn" :loading="tableLoading" @click="onSearch"/>
      </q-card-actions>
      <scroll-area :bot-margin="0">
        <table style="width: 100%">
          <thead>
            <tr>
              <th v-for="item in columns" :key="item">{{ item }}</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td style="padding-left: 40px;">
                  <q-input borderless :label="columns[0]" dense v-model="query.username" filled style="width:85%;">
                      <template v-slot:default>
                          <q-icon name="search" />
                      </template>
                  </q-input>
              </td>
              <td style="padding-left: 40px;">
                  <q-input borderless :label="columns[1]" dense v-model="query.email" filled style="width:85%;">
                      <template v-slot:default>
                          <q-icon name="search" />
                      </template>
                  </q-input>
              </td>
            </tr>
            <tr v-for="item in dataSource" :key="item.id" class="pined-row-seperator">
              <td>{{item.username}}</td>
              <td>{{item.email}}</td>
              <td>
                  <q-btn size="xs" v-if="isShowConfirm(item)" outline rounded color="primary" label="Confirm" :loading="item.confirmLoading" @click="confirmValue(item)"></q-btn>
              </td>
            </tr>
          </tbody>
        </table>
        <div class="row justify-center q-mt-md q-mb-md">
          <q-pagination
            v-model="tablePagination.page"
            :max="pagesNumber"
            input-class="text-gray-10"
            max-pages="5"
            input
            direction-links
          />
        </div>
      </scroll-area>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive, onBeforeUnmount, watch } from 'vue';
import TabContainer from '../container/TabContainer.vue';
import { RepairOrderTask, searchTaskType } from 'src/services/type';
import {
  bulkUpdateResult,
  checkTaskGroup,
  fetchRemoveNewAddOrderTask,
  getRepairOrderTasks,
} from 'src/services/repairOrderTaskService';
import { resolveDjangoUrl } from 'src/boot/axios';
import { createTask, addTaskUser } from 'src/services/tasksService';
import { useQuasar } from 'quasar';
import AssignOrderTask from 'src/components/maintenance/AssignOrderTask.vue';
import { formatDateTimeString } from 'src/utils/dateUtils';
import { useUser } from 'src/stores/userStore';
import ScrollArea from 'src/components/ScrollArea.vue'
import eformIcon from 'src/assets/style/Icon.png';
import MyDialog from '../container/MyDialog.vue';
import delImg from 'src/assets/style/delImgs.png';
import { selectUserEmail } from 'src/services/userService';

const props = withDefaults(
  defineProps<{
    orderId: number;
    role: 'checker' | 'tester';
    stock_code: string;
    parent: boolean;
    isReadOnly: boolean;
    display:'cur_tab'|'final_tab'
    isHideCol: boolean,
    isUpdateVeriAndEnd: boolean, // 是否可以修改verify by 和 endorse by 字段
  }>(),
  {
    role: 'checker',
    isHideCol: false,
    isUpdateVeriAndEnd: false,
  }
);

const user = useUser();

const emit = defineEmits(['update']);

let originTask: RepairOrderTask[] = [];
let originNewAddTask: RepairOrderTask[] = [];

const state = reactive<{
  data: RepairOrderTask[];
  newAdd: RepairOrderTask[];
  pagination: {
    page_size: number,
    page_num: number
  }
}>({
  data: [],
  newAdd: [],
  pagination: {
    page_size: 10,
    page_num: 1,
  },
});

const align = 'left';
const cols = [
  {
    name: 'task',
    label: 'Task',
    field: 'name',
    sortable: true,
    align,
  },
  {
    name: 'result',
    label: 'Result',
    field: 'result',
    sortable: true,
    align,
  },
  {
    name: 'done_by',
    label: 'Done by',
    field: 'done_by',
    sortable: true,
    align,
  },
  {
    name: 'verify_by',
    label: 'Verify by',
    field: 'verify_by',
    sortable: true,
    align,

  },
  {
    name: 'endorse_by',
    label: 'Endorse by',
    field: 'endorse_by',
    sortable: true,
    align,
  },
  {
    name: 'eform',
    label: 'E-form',
    field: 'has_eform',
    sortable: true,
    align,
  },
  {
    name: 'action',
    label: 'Action',
    field: 'action',
    headerStyle:'width: 70px !important',
    align,
  },
];
const $q = useQuasar();

const assignTask = ref(false);
const task = ref('');
const description = ref('');

const p_stock_code = ref('');
const stock_id = ref();

const tablePagination = ref({ rowsPerPage: 10, page: 1 });
const SearchDialog = ref(false); // 搜索弹窗
const searchInfo = ref<searchTaskType>({
  username: JSON.parse(localStorage.getItem('taskRecord') || '{}')?.username || '',
  email: JSON.parse(localStorage.getItem('taskRecord') || '{}')?.email || '',
});
const dataSource = ref([]); // 数据源
const columns = ref(['Username', 'E-mail Address', 'Actions']);
const tableLoading = ref(false); // table 加载loading
const query = ref({
  username: '',
  email: '',
});
const dataSourceCopy = ref([]); // 拷贝一份数据源
const pagesNumber = ref(0);

function closeDialog() {
  assignTask.value = false;
}

function onUpdateTask() {
  console.log('update');
  
  initData();
}

async function initData() {
  const data = await getRepairOrderTasks(props.orderId);
console.log(data);

  if (data && data.length > 0) {
    state.data = data
      .filter((r) => r.role == props.role)
      .filter((i)=>i.stock_item_task!=null)
      .filter((s) => s.stock_code == props.stock_code)
      .filter((c) => {
        if (props.display=='cur_tab'){
          return c.cur_tab
        }
        if (props.display=='final_tab'){
          return c.final_tab
        }
      });
    console.log( state.data );
    
    state.newAdd = data
      .filter((r) => r.role == props.role) 
      .filter((i)=>i.stock_item_task==null)
      .filter((s) => s.stock_code == props.stock_code)
      .filter((c) => {
        if (props.display=='cur_tab'){
          return c.cur_tab
        }
        if (props.display=='final_tab'){
          return c.final_tab
        }
      });;
    originTask = JSON.parse(JSON.stringify(state.data));
    originNewAddTask = JSON.parse(JSON.stringify(state.newAdd));
  }
}

function getEformUrl(rot: RepairOrderTask) {

    return `${resolveDjangoUrl()}/cews/repairordertasks/${rot.id}/eform`;
  
}

function goEform(rot: RepairOrderTask) {
  if (rot.has_eform) {
    window.open(`${resolveDjangoUrl()}/cews/repairordertasks/${rot.id}/eform`);
  }
}

async function saveFn() {
  // check diff
  setTimeout(async () => {
    const diff = state.data.filter((r, i) => {
      if (r.has_eform) {
        return false;
      }
      return r.role_result != originTask[i].role_result;
    });    
    // make object of id:role_result
    const data = diff.map((r) => ({ id: r.id, result: r.role_result }));
    await bulkUpdateResult(data);
    originTask = JSON.parse(JSON.stringify(state.data));
    emit('update');
    initData();
  }, 10);

}

async function saveNewAddFn() {
  // check diff
  setTimeout(async () => {
    const diff = state.newAdd.filter((r, i) => {
      if (r.has_eform) {
        return false;
      }
      return r.role_result != originNewAddTask[i].role_result;
    });    
    // make object of id:role_result
    const newAdd = diff.map((r) => ({ id: r.id, result: r.role_result }));
    await bulkUpdateResult(newAdd);
    originNewAddTask = JSON.parse(JSON.stringify(state.newAdd));
    emit('update');
    initData();
  }, 10);

}

function handleVisibilityChange() {
  if (document.visibilityState === 'visible') {
    // Call your API to refresh data here
    initData();
    emit('update');
  }
}

function deleteFn(id: number) {
  $q.dialog({
    title: 'Confirm',
    message: 'Are you sure to delete this record?',
    cancel: true,
  }).onOk(async () => {
    const res = await fetchRemoveNewAddOrderTask(id);
    if (res) {
      initData();
      emit('update');
    }
  });
}

function getOverAllresultCss(row:RepairOrderTask){
  let { done_by, role, is_endorse_required, verify_by, endorse_by, role_result, done_by_datetime } = row;
  if(role=="tester" && done_by && done_by_datetime) return '';
  if(is_endorse_required){
      if (endorse_by){
        return ''
      }else{
        return 'fail'
      }
  }else{
    if (verify_by){
        return ''
      }else{
        return 'fail'
      }
  }
}


function onClear() {
  task.value = '';
  description.value = '';
}

/**
 * current Task Cols with New ADD Tasks List
 */
const currentTaskCol =  computed(()=> {
  return cols.filter(f=>!['verify_by', 'endorse_by'].includes(f.name));
})

onMounted(() => {
  initData();
  document.addEventListener('visibilitychange', handleVisibilityChange);
});

onBeforeUnmount(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange);
});


/**
 * 查询用户数据信息（姓名、邮箱）
 */
 const selectUserEmailList = async ()=> {
  let { username, email } = searchInfo.value;
  let searchParams = {
    username, 
    email,
    ...state.pagination,
  }
  tableLoading.value = true;
  try {
    let res = await selectUserEmail(searchParams)
    let { results=[], count=0 } = res.data;
    pagesNumber.value = Math.ceil(count / tablePagination.value.rowsPerPage);
    dataSource.value = results.map((m:any)=> {
      return {
        ...m,
        confirmLoading: false,
      }
    });
    dataSourceCopy.value = results;
  } catch (error) {
    
  }finally {
    tableLoading.value = false;
  }
}
const taskData = ref({}); // 当前task的数据
const taskType = ref(); // 要修改的类型
/**
 * 打开搜索弹窗
 * @params type verify endorse
 */
const openSearchDialog =(row={}, type:string)=> {
    taskData.value = {};
    taskData.value = row;
    taskType.value = type;
    selectUserEmailList();
    SearchDialog.value = true;
}

watch(query.value, () => {
    // 调用筛选函数
    filterList();
});

interface itemFilterType {
  username: string;
  email: string;
}
const filterList = ()=> {
  dataSource.value = dataSourceCopy.value.filter((item:itemFilterType) => {
    let { username, email  } = query.value;
    const conditionCheck =
        item.username.includes(username) &&
        item.email.includes(email);
        return conditionCheck;
    })
}

/**
 * 搜索
 */
const onSearch = ()=> {
  selectUserEmailList();
  localStorage.setItem('taskRecord', JSON.stringify(searchInfo.value));
}

watch(()=> (tablePagination.value.page), (val)=> {
    state.pagination = {
      ...state.pagination,
      page_num: val
    }
    selectUserEmailList();
}, {
  immediate: true,
})

/**
 * 确认选择的数据
 * @param row 当前行数据 
 */
const confirmValue = async (row:any)=> {
  let { id: check_user_id,} = row;
  let { id: repair_order_task_id } = taskData.value as any;
  let submitData = {
    repair_order_task_id, 
    check_user_id, 
    flow: taskType.value
  }
  row.confirmLoading = true;
  try {
    await addTaskUser(submitData);
    onUpdateTask();
    $q.notify({
        message: 'Success',
        color:'positive'
    })
    SearchDialog.value = false;
  } catch (error) {
    $q.notify({
        message: error?.message || 'Error',
        color:'negative'
    })
  } finally {
    row.confirmLoading = false;
  }
}

/**
 * 是否显示确认按钮
 */
const isShowConfirm = (row={})=> {
  let { verify_user, endorse_user } = taskData.value as any;
  let { id } = row as any;
  switch (taskType.value) {
    case 'verify':
      return verify_user.id !== id;
    case 'endorse':
      return endorse_user.id !== id;
    default:
      return true;
  }
}
</script>
<style scoped lang="scss">
.content {
  width: 100%;
  margin: 0 auto;
}
.flex1 {
  flex: 1;
}
.mt20 {
  margin-top: 20px;
}
.flex-center {
  display: flex;
  justify-content: center;
}
table {
  border-collapse: collapse;
  table-layout: fixed;
}

table thead tr th {
  border-bottom: 1px solid #d9d9d9;
}

td {
  padding: 0.5rem;
}

table thead {
  position: sticky;
  top: 0;
  background-color: white;
  z-index: 10;
}
table {
  border-collapse: collapse;
  table-layout: fixed;
}
table th {
  color: #000;
}

table th,
table td {
  /* Added padding for better layout after collapsing */
  padding: 4px 8px;
}

table tbody tr {
  border-top: 1px solid white;
  border-bottom: 1px solid #0000001f;

  &:hover {
    opacity: 0.9;
  }
}

table tbody tr,
table tbody td {
  height: 46px !important;
}

.pointer-cursor {
  cursor: pointer;
}

.pined-row-seperator {
  text-align: center;
}

.table-algin {
  text-align: center;
}
.justify-center {
    display: flex;
    justify-content: center;
}
.delImgClass {
  width: 20px;
  height: 20px;
}
</style>
